<template>
  <div class="app">
    <h1>App</h1>
    <p>接收到的学校信息:{{ schoolMessage }}</p>
    <p>接收到的学生信息:{{ studentMessage }}</p>

    <!-- 通过父组件给子组件传递函数类型的 props实现: 子给父传递数据 -->
    <school-com :getSchoolMessage="getSchoolMessage"></school-com>

    <!-- 通过父组件给子组件绑定一个自定义事件实现: 子给父传递数据(第一种写法: 使用@或者v-on) -->
    <!-- <student-com @custom_event="getStudentMessage"></student-com> -->

    <!-- 通过父组件给子组件绑定一个自定义事件实现: 子给父传递数据(第二种写法: 使用ref) -->
    <student-com ref="getStudent"></student-com>
  </div>
</template>

<script>
// 引入School组件
import Student from "./components/Student.vue";
import School from "./components/School.vue";

export default {
  name: "App",
  components: {
    "student-com": Student,
    "school-com": School,
  },
  data() {
    return {
      schoolMessage: "",
      studentMessage: "",
    };
  },
  methods: {
    getSchoolMessage(...val) {
      this.schoolMessage = val;
    },
    getStudentMessage(...val) {
      console.log(val);
      this.studentMessage = val;
    },
  },
  mounted() {
    console.log(this.$refs.getStudent);

    // 拿到 Student组件实例 使用 $on 方法监听当前实例上的自定义事件.
    // 事件可以由 $emit 触发. 回调函数会接收所有传入事件触发函数的额外参数.
    this.$refs.getStudent.$on("custom_event", this.getStudentMessage);
  },
};
</script>

<style lang="sass">
$padding: 10px
$margin: 10px

.app
  background-color: gray
  padding: $padding

  h1
    background-color: pink
    text-align: center
    margin: $margin

  p
    background-color: yellowgreen
    padding: $padding
    margin: $margin
</style>
